package cmpe451.group7.dbserver.util;

import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Utils {
	public static <T> void JSONWriter(List<T> entityList, PrintWriter writer) {
		Gson gson = new GsonBuilder().create();

		int size = entityList.size();

		if (size > 0) {
			writer.printf("{ result=\"success\", count:\"%d\", data: [", size);
			Iterator<T> iterator = entityList.iterator();
			gson.toJson(iterator.next(), writer);

			while (iterator.hasNext()) {
				writer.print(",");
				gson.toJson(iterator.next(), writer);
			}
			writer.print("]}");
		} else {
			writer.printf("{ result=\"success\", count:\"0\", data:[] }");
		}

	}

	public static <T> void JSONWriter(T entity, PrintWriter writer) {
		Gson gson = new GsonBuilder().create();
		if(entity != null){
			writer.printf("{ result=\"success\", count:\"%d\", data: ", 1);
			gson.toJson(entity, writer);
			writer.print("}");
		} else{
			writer.printf("{ result=\"success\", count:\"%d\", data: {} }", 0);
		}
	}
}
